package lucene.server.cdc.mysql.util;

import lucene.server.common.dbmeta.ColumnMeta;
import lucene.server.common.event.EventData;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ConvertUtil {

    public static void getUpdateMap(EventData eventData, Map.Entry<Serializable[], Serializable[]> data, List<ColumnMeta> columnMap){
        if (data == null){
            return;
        }
        for (ColumnMeta column : columnMap){
            eventData.getBefore().put(column.getColumnName(),convertValue(data.getKey()[column.getColumnIndex()],column));
            eventData.getAfter().put(column.getColumnName(), convertValue(data.getValue()[column.getColumnIndex()],column));
        }
    }
    public static void getInsertOrDeleteMap(EventData eventData, Serializable[] data, List<ColumnMeta> columnMap){
        if (data == null){
            return;
        }
        for (ColumnMeta column : columnMap){
            eventData.getAfter().put(column.getColumnName(), convertValue(data[column.getColumnIndex()],column));
        }
    }

    public static Object convertValue(Object data,ColumnMeta column){
        if (data == null){
            return null;
        }
        if (column.isStringType){
            return new String ((byte[])data, StandardCharsets.UTF_8);
        }else if (column.isDateTimeType){
            try{
                // 将Date转换为ZonedDateTime
                ZonedDateTime zonedDateTime = ((Date)data).toInstant().atZone(ZoneId.systemDefault());
                // 减去8小时
                ZonedDateTime subtractedDateTime = zonedDateTime.minus(8, ChronoUnit.HOURS);
                // 将ZonedDateTime转换回Date
                return Date.from(subtractedDateTime.toInstant());
            }catch (Exception e){
                System.out.println(column.getColumnName()+"日期转换失败！" + e.getMessage());
                return null;
            }
        }else if(column.isBinaryType){
            return new String ((byte[])data);
        }
        else{
            return data;
        }
    }
}
